package com.yaolin.generator.api.enjoy;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.template.Engine;
import com.yaolin.generator.api.Generator;
import com.yaolin.generator.api.Table;
import com.yaolin.generator.api.enjoy.mapper.Mapper;
import com.yaolin.generator.api.enjoy.mapper.TableDTO;

/**
 * 执行maven-install, 详见pom.xml plugins的配置
 * @author yaolin
 *
 */
public class GeneratorWithEnjoy implements Generator {

	/**
	 * 根据数据库表生成相关代码
	 * @param templateFileDir 模板文件目录（带盘符）
	 * @param basePackageName 项目包名
	 * @param javaFileDir java文件目录
	 * @param resourceFileDir 资源文件目录
	 * @param jsFileDir js文件目录
	 * @param viewFileDir 视图文件目录
	 * @param table 数据库表信息
	 * @see Table
	 */
	@Override
	public void generate(String templateFileDir, String basePackageName,
		String javaFileDir, String resourceFileDir, String jsFileDir, String viewFileDir, Table table) {
		
		Map<String, Object> root = new HashMap<String,Object>();
		TableDTO tableDTO = Mapper.mapToDTO(table);
		root.put("basePackageName", basePackageName);
		putExtraData(root, table);
		root.put("tableDTO", tableDTO);
		
		// 将报名转化成路径
		if (!javaFileDir.endsWith(File.separator)) {
			javaFileDir += File.separator;
		}
		String javaPath = javaFileDir + basePackageName.replace(".", File.separator) + File.separator;
		renderFile(root, templateFileDir, "BaseModel.html", javaPath, "BaseModel.java");
	}

	
	private Engine engine = Engine.use();
	/**
	 * 渲染模板
	 */
	public void renderFile(Map<String, Object> root, String templateDir, String templateName, String fileDir, String fileName) {
		
		File dir = new File(fileDir);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
		
		try ( FileWriter fw = new FileWriter(new File(fileDir + fileName)); ) {
			engine.setBaseTemplatePath(templateDir);
			engine.addSharedObject("StrKit", new StrKit());
			engine.getTemplate(templateName).render(root, fw);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 附加额外数据
	 */
	private void putExtraData(Map<String, Object> root, Table table) {
		String e = table.getName();
		int i = e.indexOf("_");
		// 获取模块名
		String modual = "";
		if (i != -1) {
			modual = e.substring(0, i);
			e = e.substring(i + 1);
		}
		root.put("modual", modual);
		// 获取实体名
		String[] item = e.split("\\_");
		StringBuffer sb = new StringBuffer();
		for (String it : item) {
			sb.append(it.substring(0, 1).toUpperCase() + it.substring(1));
		}
		root.put("entityName", sb.toString());
	}

}
